package com.ruoyi.system.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * @author zql
 * @date 2022-10-28
 */
public class WrapperUtils {

    /**
     * map中的值直接生成eq语句
     * 后台list查询条件常用
     *
     * @param queryWrapper
     * @param map
     * @return
     */
    public static QueryWrapper MapAddEqualToQueryWrapper(QueryWrapper queryWrapper, Map map){
        for (Object key : map.keySet()) {
            if (ObjectUtil.isNotEmpty(map.get(key))){
                queryWrapper.eq(StrUtil.toUnderlineCase(String.valueOf(key)), map.get(key));
            }
        }
        return queryWrapper;
    }

    /**
     * 当查询字段是日期类型时，则忽略时分秒，即查询当天整天的数据；如果不是日期类型则进行等值比较
     */
    public static QueryWrapper MapAddEqualToQueryIgnoreTimeWrapper(QueryWrapper queryWrapper, Map map){
        for (Object key : map.keySet()) {
            if (ObjectUtil.isNotEmpty(map.get(key))) {
                // 字段名中带time或date的，则默认是日期类型
                if (((String) key).contains("Time") || ((String) key).contains("Date")) {
                    // 时间戳
                    Long time = (Long) map.get(key);
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime dayStartTime = Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault()).toLocalDateTime();
                    LocalDateTime dayEndTime = dayStartTime.plusDays(1).minusSeconds(1);
                    queryWrapper.between(StrUtil.toUnderlineCase(String.valueOf(key)), dayStartTime.format(df), dayEndTime.format(df));
                } else {
                    queryWrapper.eq(StrUtil.toUnderlineCase(String.valueOf(key)), map.get(key));
                }
            }
        }
        return queryWrapper;
    }
}
